package com.learning.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

/**
 * @author wangyunyun
 */
@Slf4j
@Service
public class AsyncService {

	/**
	 * 无返回值的异步任务
	 */
	@Async("commonThreadPool")
	public void processTask(String taskId) throws InterruptedException {
		long start = System.currentTimeMillis();
		try {
			// 模拟业务处理
			Thread.sleep(2000);
			log.info(Thread.currentThread()
					.getName() + " 完成任务: " + taskId + " | 耗时: " + (System.currentTimeMillis() - start) + "ms");
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			throw new RuntimeException("任务被中断: " + taskId, e);
		}
	}

	/**
	 * 带返回值的异步任务（Future方式）
	 */
	@Async("commonThreadPool")
	public Future<String> processWithResult(String input) {
		try {
			Thread.sleep(1000);
			return new AsyncResult<>("处理结果: " + input.toUpperCase());
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			return new AsyncResult<>("处理失败");
		}
	}

	/**
	 * 带返回值的异步任务（CompletableFuture方式 - Java8+推荐）
	 */
	@Async("commonThreadPool")
	public CompletableFuture<Integer> calculateAsync(int number) {
		return CompletableFuture.supplyAsync(() -> {
			try {
				// 模拟复杂计算
				Thread.sleep(500);
				return number * number;
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				throw new RuntimeException("计算中断");
			}
		});
	}

	/**
	 * 异步异常处理示例
	 */
	@Async("commonThreadPool")
	public void processWithException() {
		try {
			// 模拟可能出错的业务
			if (System.currentTimeMillis() % 2 == 0) {
				throw new IllegalStateException("模拟业务异常");
			}
			log.info("任务成功执行");
		} catch (Exception e) {
			// 这里应该添加实际异常处理逻辑
			log.info("捕获异步异常: " + e.getMessage());
			// 可记录日志/发送告警等
			// 重新抛出以触发全局异常处理
			throw e;
		}
	}

}
